﻿using BW.Mes.WinForms.Process.OperationModel;
using DevExpress.XtraEditors;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace BW.Mes.WinForms.Process.AuditProcess
{
    public partial class AuditProcessForm : DevExpress.XtraEditors.XtraForm
    {
        private readonly HttpClient _httpClient;
        private readonly string _apiBaseUrl = "http://120.26.197.100:8022";
        private string searchWorkflowId = "";
        private string searchStepName = "";

        // 分页管理器
        private PaginationManager paginationManager;
        
        public AuditProcessForm()
        {
            InitializeComponent();

            // 初始化分页管理器
            paginationManager = new PaginationManager();
            paginationManager.PageChanged += PaginationManager_PageChanged;

            _httpClient = new HttpClient();
            _httpClient.DefaultRequestHeaders.Accept.Add(
                new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

            this.Load += AuditProcessForm_Load;
            this.checkButton1.Click += CheckButton1_Click;
        }

        private void PaginationManager_PageChanged(object sender, EventArgs e)
        {
            // 当页码或页大小改变时重新加载数据
            LoadAuditProcessData();
        }

        private void AuditProcessForm_Load(object sender, EventArgs e)
        {
            try
            {
                // 检查是否已有分页面板，有则移除
                Control existingPanel = panelControl2.Controls["paginationPanel"];
                if (existingPanel != null)
                {
                    panelControl2.Controls.Remove(existingPanel);
                }
                
                // 初始化分页控件
                paginationManager.Initialize(panelControl2);
                
                // 设置列绑定
                SetupGridViewColumns();
                
                // 初始加载数据
                LoadAuditProcessData();
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"窗体加载失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void SetupGridViewColumns()
        {
            gridView1.OptionsBehavior.Editable = false;
            gridView1.OptionsView.ShowGroupPanel = false;

            // 设置列与数据字段的绑定关系
            gridColumn1.FieldName = "Id";
            gridColumn2.FieldName = "WorkflowId";
            gridColumn3.FieldName = "StepId";
            gridColumn4.FieldName = "StepName";
            gridColumn5.FieldName = "AuditUserId";
            gridColumn6.FieldName = "AuditUserName";
            gridColumn7.FieldName =  "Status";
            gridColumn8.FieldName = "Remark";
            gridColumn9.FieldName = "ExecutionPointer";
            gridColumn10.FieldName = "AuditType";
            
            // 设置列宽自适应
            foreach (DevExpress.XtraGrid.Columns.GridColumn col in gridView1.Columns)
            {
                col.BestFit();
            }
        }

        private void CheckButton1_Click(object sender, EventArgs e)
        {
            try
            {
                // 获取搜索条件
                searchWorkflowId = textEdit1.Text.Trim();
                searchStepName = textEdit2.Text.Trim();
                
                // 搜索时重置为第一页
                paginationManager.ResetToFirstPage();
                
                // 执行查询
                LoadAuditProcessData();
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"查询失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void LoadAuditProcessData()
        {
            try
            {
                // 显示加载中提示
                Cursor = Cursors.WaitCursor;
                
                // 构建API URL，添加分页参数
                string url = $"{_apiBaseUrl}/T5/OperationModel/ShowAuditProcess?PagIndex={paginationManager.CurrentPage}&PagSize={paginationManager.PageSize}";
                
                // 添加搜索参数
                if (!string.IsNullOrEmpty(searchWorkflowId))
                {
                    url += $"&WorkflowId={Uri.EscapeDataString(searchWorkflowId)}";
                }
                
                if (!string.IsNullOrEmpty(searchStepName))
                {
                    url += $"&StepName={Uri.EscapeDataString(searchStepName)}";
                }
                
                Console.WriteLine($"API请求URL: {url}");
                
                // 发起API请求
                GetAuditProcessDataAsync(url);
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"加载数据失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                Cursor = Cursors.Default;
            }
        }

        private async void GetAuditProcessDataAsync(string url)
        {
            try
            {
                // 发送HTTP请求
                var response = await _httpClient.GetAsync(url);
                response.EnsureSuccessStatusCode();

                // 获取响应内容
                var content = await response.Content.ReadAsStringAsync();
                Console.WriteLine($"API响应: {content}");

                // 反序列化响应数据
                var apiResult = JsonConvert.DeserializeObject<PagingApiResult<List<AuditProcessModel>>>(content);

                if (apiResult != null && apiResult.success == 200 && apiResult.pagingdata != null)
                {
                    // 更新分页信息
                    if (apiResult.totalCount > 0)
                    {
                        paginationManager.UpdatePagingData(apiResult.totalCount);
                    }
                    else if (apiResult.pagingdata.Count > 0)
                    {
                        // 如果API未返回总数，但有数据，则使用当前数据数量作为总数
                        paginationManager.UpdatePagingData(apiResult.pagingdata.Count * paginationManager.TotalPages);
                    }

                    // 绑定数据到GridControl
                    gridControl1.DataSource = apiResult.pagingdata;
                    
                    // 刷新GridView
                    gridControl1.RefreshDataSource();
                    gridView1.RefreshData();
                    gridView1.BestFitColumns();

                    Console.WriteLine($"已加载 {apiResult.pagingdata.Count} 条记录，总计 {apiResult.totalCount} 条");
                }
                else
                {
                    // 处理API返回错误
                    string errorMessage = apiResult != null ? apiResult.message : "未知错误";
                    XtraMessageBox.Show($"获取数据失败: {errorMessage}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    
                    // 清空数据源
                    gridControl1.DataSource = null;
                    
                    // 更新分页信息为0条记录
                    paginationManager.UpdatePagingData(0);
                }
            }
            catch (HttpRequestException httpEx)
            {
                XtraMessageBox.Show($"HTTP请求错误: {httpEx.Message}\n请确认API服务是否启动并可访问。", "网络错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"加载数据时发生错误: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                // 恢复光标
                Cursor = Cursors.Default;
            }
        }
    }

    // 审批流程数据模型
    public class AuditProcessModel
    {
        public long Id { get; set; }
        public string WorkflowId { get; set; }
        public string StepId { get; set; }
        public string StepName { get; set; }
        public long AuditUserId { get; set; }
        public string AuditUserName { get; set; }
        public string Status { get; set; }
        public string Remark { get; set; }
        /// <summary>
        /// 操作节点
        /// </summary>
        public string ExecutionPointer { get; set; }
        /// <summary>
        /// 操作类型
        /// </summary>
        public string AuditType { get; set; }
    }
}